<!-- src/views/teacher/GradeManagement.vue -->
<template>
  <div class="grade-management">
    <div class="header">
      <el-page-header @back="$router.go(-1)" title="返回">
        <template #content>
          <span class="title">成绩评定</span>
        </template>
      </el-page-header>
    </div>

    <el-card class="filter-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchParams.keyword"
            placeholder="搜索学生姓名或学号"
            clearable
            @clear="resetSearch"
            @keyup.enter="fetchPendingEvaluations"
          >
            <template #append>
              <el-button icon="Search" @click="fetchPendingEvaluations" />
            </template>
          </el-input>
        </el-col>

        <el-col :span="6">
          <el-button @click="resetSearch">重置</el-button>
        </el-col>
      </el-row>
    </el-card>

    <el-card>
      <el-table
        :data="pendingEvaluations"
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column prop="studentName" label="学生姓名" width="100" />
        <el-table-column prop="studentId" label="学号" width="120" />
        <el-table-column prop="companyName" label="实习企业" min-width="180" />
        <el-table-column prop="positionTitle" label="实习岗位" min-width="150" />
        <el-table-column prop="startDate" label="开始日期" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.startDate) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="viewEvaluationHistory(scope.row)">评定记录</el-button>
            <el-button
                size="small"
                :type="getEvaluationButtonInfo(scope.row).type"
                :disabled="getEvaluationButtonInfo(scope.row).disabled"
                @click="handleEvaluation(scope.row)"
            >
              {{ getEvaluationButtonInfo(scope.row).text }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        layout="total, prev, pager, next, jumper"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        class="pagination"
      />
    </el-card>

    <!-- 评定记录对话框 -->
    <el-dialog
      v-model="historyDialogVisible"
      title="评定记录"
      width="700px"
    >
      <div v-if="evaluationHistory.length > 0">
        <el-table :data="evaluationHistory" style="width: 100%">
          <el-table-column prop="evaluatorType" label="评定人类型" width="120">
            <template #default="scope">
              {{ getEvaluatorTypeLabel(scope.row.evaluatorType) }}
            </template>
          </el-table-column>
          <el-table-column prop="score" label="评分" width="80" />
          <el-table-column prop="comment" label="评语" min-width="150" />
          <el-table-column prop="evaluatedAt" label="评定时间" width="150">
            <template #default="scope">
              {{ formatDate(scope.row.evaluatedAt) }}
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-else>
        <el-empty description="暂无评定记录" />
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="historyDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 成绩评定对话框 -->
    <el-dialog
      v-model="evaluateDialogVisible"
      :title="isEditing ? '修改成绩' : '成绩评定'"
      width="500px"
    >
      <el-form
        :model="evaluationForm"
        :rules="evaluationRules"
        ref="evaluationFormRef"
        label-width="100px"
      >
        <el-form-item label="学生姓名">
          <el-input v-model="evaluationForm.studentName" disabled />
        </el-form-item>

        <el-form-item label="实习企业">
          <el-input v-model="evaluationForm.companyName" disabled />
        </el-form-item>

        <el-form-item label="评分" prop="score">
          <el-input-number
            v-model="evaluationForm.score"
            :min="0"
            :max="100"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="评语" prop="comment">
          <el-input
            v-model="evaluationForm.comment"
            type="textarea"
            placeholder="请输入评语"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="evaluateDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitEvaluation"
            :loading="evaluateLoading"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useTeacherStore } from '../../store/teacher'
import { ElMessage } from 'element-plus'

const teacherStore = useTeacherStore()

const pendingEvaluations = ref([])
const evaluationHistory = ref([])
const loading = ref(false)
const historyDialogVisible = ref(false)
const evaluateDialogVisible = ref(false)
const evaluateLoading = ref(false)
const isEditing = ref(false)
const selectedInternship = ref(null)

// 搜索参数
const searchParams = reactive({
  keyword: ''
})

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 成绩评定表单
const evaluationForm = reactive({
  studentName: '',
  companyName: '',
  score: null,
  comment: ''
})

// 表单验证规则
const evaluationRules = {
  score: [
    { required: true, message: '请输入评分', trigger: 'change' },
    { type: 'number', min: 0, max: 100, message: '评分应在0-100之间', trigger: 'change' }
  ],
  comment: [{ required: true, message: '请输入评语', trigger: 'blur' }]
}

const evaluationFormRef = ref()

// 获取待评定列表并加载评定信息
const fetchPendingEvaluations = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage - 1,
      size: pagination.pageSize,
      ...searchParams
    }

    const response = await teacherStore.getPendingEvaluations(params)
    const internships = response.content || response

    // 为每个实习获取评定记录
    for (const internship of internships) {
      try {
        const evalResponse = await teacherStore.getStudentEvaluationsWithCache(internship.studentId)
        const evaluations = evalResponse.content || evalResponse

        // 查找该实习的评定记录（根据实习ID匹配）
        const internshipEvaluation = evaluations.find(evaluation => evaluation.internshipId === internship.id)
        if (internshipEvaluation) {
          internship.score = internshipEvaluation.score
        }
      } catch (error) {
        console.warn(`获取学生${internship.studentId}的评定记录失败:`, error)
      }
    }

    pendingEvaluations.value = internships
    pagination.total = response.totalElements || 0
  } catch (error) {
    ElMessage.error('获取待评定列表失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 获取评定按钮信息
const getEvaluationButtonInfo = (internship) => {
  if (internship.score !== undefined && internship.score !== null) {
    return {
      text: internship.score,
      type: 'success',
      disabled: true
    }
  } else {
    return {
      text: '成绩评定',
      type: 'primary',
      disabled: true
    }
  }
}

// 处理评定操作
const handleEvaluation = (internship) => {
  // 只有无成绩的项目才能进行评定
  if (internship.score === undefined || internship.score === null) {
    evaluateStudent(internship)
  }
  // 已有成绩的项目不执行任何操作
}

// 重置搜索
const resetSearch = () => {
  searchParams.keyword = ''
  pagination.currentPage = 1
  // 清除缓存并重新获取数据
  teacherStore.clearStudentEvaluationsCache()
  fetchPendingEvaluations()
}

// 分页处理
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  fetchPendingEvaluations()
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  fetchPendingEvaluations()
}

// 查看评定记录
const viewEvaluationHistory = async (internship) => {
  try {
    const response = await teacherStore.getStudentEvaluationsWithCache(internship.studentId)
    evaluationHistory.value = response.content || response
    historyDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取评定记录失败: ' + (error.response?.data?.message || error.message))
  }
}

// 成绩评定
const evaluateStudent = (internship) => {
  isEditing.value = false
  selectedInternship.value = internship
  evaluationForm.studentName = internship.studentName
  evaluationForm.companyName = internship.companyName
  evaluationForm.score = null
  evaluationForm.comment = ''
  evaluateDialogVisible.value = true

  // 清除验证状态
  nextTick(() => {
    if (evaluationFormRef.value) {
      evaluationFormRef.value.clearValidate()
    }
  })
}
// 提交成绩评定
const submitEvaluation = async () => {
  if (!evaluationFormRef.value) return

  await evaluationFormRef.value.validate(async (valid) => {
    if (valid) {
      evaluateLoading.value = true
      try {
        const data = {
          internshipId: selectedInternship.value.id,
          studentId: selectedInternship.value.studentId,
          score: evaluationForm.score,
          comment: evaluationForm.comment
        }

        await teacherStore.evaluateInternship(data)
        ElMessage.success(isEditing.value ? '成绩修改成功' : '成绩评定成功')
        evaluateDialogVisible.value = false
        // 清除缓存并重新获取数据
        teacherStore.clearStudentEvaluationsCache()
        fetchPendingEvaluations()
      } catch (error) {
        ElMessage.error('评定失败: ' + (error.response?.data?.message || error.message))
      } finally {
        evaluateLoading.value = false
      }
    }
  })
}

// 获取评定人类型标签
const getEvaluatorTypeLabel = (type) => {
  switch (type) {
    case 1: return '学校导师'
    case 2: return '企业导师'
    default: return '未知'
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString()
}

onMounted(() => {
  fetchPendingEvaluations()
})
</script>

<style scoped>
.header {
  margin-bottom: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.grade-detail {
  margin-bottom: 20px;
}
</style>
